package com.hypo.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hypo.business.domain.GoodCategory;
import com.hypo.business.mapper.GoodCategoryMapper;
import com.hypo.business.service.GoodCategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class GoodCategoryServiceImpl extends ServiceImpl<GoodCategoryMapper, GoodCategory> implements GoodCategoryService {
    private final GoodCategoryMapper goodCategoryMapper;

    @Override
    public Object find(List<GoodCategory> all) {
        List<GoodCategory> parents = all.stream().filter(a -> a.getParentId() == 0).toList();
        List<GoodCategory> children = all.stream().filter(a -> a.getParentId() > 0).toList();

        parents.forEach(p -> findChildren(p, children));
        return parents;

    }

    private void findChildren(GoodCategory p, List<GoodCategory> children) {
        List<GoodCategory> list = children.stream().filter(c -> Objects.equals(c.getParentId(), p.getId())).toList();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(l -> findChildren(l, children));
        }
        p.setChildren(list);
    }
}
